import axios from 'axios';
import router from '../router';
import store from '../store';
//引入原生node字符串查询方法
import qsString from 'querystring'


let baseURL = '/api'


//请求拦截
axios.interceptors.request.use(req=>{
    //设置请求头
    if(req.url!=baseURL +'/userlogin'){
    req.headers.authorization = store.getters.getUserInfo.token;
    }
    return req
})

//响应拦截
axios.interceptors.response.use(res=>{
    //全局拦截错误
    if(res.data.msg == "请设置请求头,并携带验证字符串"){
        alert(res.data.msg);
        router.push("/login");
    }else if(res.data.msg == "登录已过期或访问权限受限"){
        alert(res.data.msg);
        router.push('/login');
    }else{
        return res.data;
    }
    
});


//独立封装get方法
export const get = (url,params={})=>{
    return new Promise((resolve,reject)=>{
        axios
        .get(baseURL+url,{
            params
        })
        .then((res)=>{
            resolve(res);
        })
        .catch((err)=>{
            reject(err);
        });
    });
};


//独立封装post方法
//isFile判断是否含有文件
export const post = (url,params={},isFile=false)=>{
    let data = null
    //有文件
    if(isFile){
        data = new FormData()
        for(let i in params){
            console.log(i,'fromdata');
            
            data.append(i,params[i])
        }
    }else{
        data = qsString.stringify(params)
    }
    return new Promise((resolve,reject)=>{
        axios.post(baseURL+url,data)
        .then(res=>{
            resolve(res)
        })
        .catch(err=>{
            reject(err)
        })
    })
}

